package com.nexgo.payment.aop;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.nexgo.payment.App;
import com.nexgo.payment.BaseTransView;
import com.nexgo.payment.aop.annotation.TransCondition;
import com.nexgo.payment.api.ApiLocationService;
import com.nexgo.payment.constrant.PreferencesConstants;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.databases.SettleInfo;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.util.StringUtils;
import com.nexgo.payment.util.TransUtils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by xiaox on 2018/1/10.
 */
@Aspect
public class TransConfigInjection implements  ApiLocationService.LocationInterface{
    private Logger mLog;
    private BaseTransView<?> mView;
    private DataSource mRepository;
    private TransData mTransData;
    private ApiLocationService mLocationService;
    private AMapLocationClient mLocationClient;
    TransConfigInjection() {
        mLog = LoggerFactory.getLogger("TransConfigInjection");
    }

    /**
     * 被@TransConditionCheck注解的类
     */
    @Pointcut("@target(com.nexgo.payment.aop.annotation.TransCondition)")
    public void annotationWithTransCondition() {
    }
    @Pointcut("@target(com.nexgo.payment.aop.annotation.ManageTransCondition)")
    public void annotationWithManageTransCondition() {
    }
    /**
     * Presenter以及子类下的构造方法
     */
    @Pointcut("execution(com.nexgo.payment.trans.*Presenter+.new(..))")
    public void construct() {
    }

    /**
     * Presenter以及子类下的getTransData方法
     */
    @Pointcut("execution(* com.nexgo.payment.trans.*Presenter+.getTransData(..))")
    public void getTransData() {

    }

    /**
     * Presenter以及子类下的onFirstAction方法
     */
    @Pointcut("execution(* com.nexgo.payment.trans.*Presenter+.onFirstAction(..))")
    public void onFirstAction() {
    }
    /*
    @Pointcut("execution(* com.nexgo.payment.trans.*Presenter+.onTransOnlineProc(..))")
    public void onTransOnlineProc() {
    }

    @Around("onTransOnlineProc() && annotationWithTransCondition()")
    public Object onTransOnlineProcBefore(ProceedingJoinPoint joinPoint) throws Throwable {
        mLog.debug("检查GPS信息");
        if ("1".equals(mRepository.getParamValue(PreferencesConstants.NEED_CHECK_GPS))) {
            mLog.debug("mTransData.getLatitude() {}",mTransData.getLatitude());
            if("0.0".equals(mTransData.getLatitude())||"0.0".equals(mTransData.getLongitude())){
                mView.showCheckGPSFail();
                return null;
            }
        }
        return joinPoint.proceed();
    }*/

//    @Before("onFirstAction() && annotationWithTransCondition()")
    @Before("onFirstAction()")
    public void firstActionBefore() {
        mLog.debug("TransConfigInjection firstActionBefore");
        if (mLocationService == null) {
            mLocationService = new ApiLocationService(App.sContext, this);
        }
            mLocationService.startLocation();
    }


    @Around("construct() && (annotationWithTransCondition()|| annotationWithManageTransCondition())")
    public Object constructProcess(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        mView = (BaseTransView<?>) args[0];
        mRepository = (DataSource) args[1];
        return joinPoint.proceed();
    }

    @AfterReturning(pointcut = "getTransData() && annotationWithTransCondition() ", returning = "transData")
    public void getTransData(TransData transData) {
        mTransData = transData;
    }

    
    @Around("onFirstAction() && annotationWithTransCondition()")
    public Object onFirstActionProcess(ProceedingJoinPoint joinPoint) throws Throwable {
        mLog.debug("检查交易前置条件");
        TransCondition conditionCheck = joinPoint.getTarget().getClass().getAnnotation(TransCondition.class);
        mLog.debug("检查是否支持的交易");
        //是否屏蔽的交易
        if (!TransUtils.isSupportTrans(mTransData.getTransType(), mRepository)) {
            mLog.debug("不支持的交易");
            mView.showUnsupported();
            return null;
        }
        mLog.debug("检查签到状态");
        //是否主管签到
        if (TransUtils.isAdminOperator(mRepository.getParamValue(PreferencesConstants.CURRENT_OPERATOR_NO))) {
            mLog.debug("当前主管签到，不能交易");
            mView.showAdminCantTrade();
            return null;
        }
        //是否需要签到
        if ("1".equals(mRepository.getParamValue(PreferencesConstants.IS_NEED_LOGIN))) {
            mLog.debug("需要重新签到");
            mView.showLoginFirst();
            return null;
        }
        if (conditionCheck.checkNeedSettle()) {
            mLog.debug("检查是否超最大交易笔数");
            //是否超过交易最大记录条数
            if (mRepository.getSuccessfulTransRecordNum() > Integer.parseInt(StringUtils.firstNonEmpty(mRepository.getParamValue(PreferencesConstants.MAX_NUMBER_OF_TRANS), "0"))) {
                mLog.debug("超过交易笔数");
                mView.showTransRecordLimit();
                return null;
            }
            mLog.debug("检查批上送是否中断");
            //是否批上送中断
            SettleInfo settleInfo = mRepository.getSettleInfo();
            if (settleInfo != null) {
                if (!settleInfo.getIsBatchUploadComplete()) {
                    mLog.debug("需要继续批上送");
                    mView.showBatchUploadFirst();
                    return null;
                }
            }
        }
        // 增加获取GPS 基站
        //是否需要校验GPS
   /*     mLog.debug("检查GPS信息");
        if ("1".equals(mRepository.getParamValue(PreferencesConstants.NEED_CHECK_GPS))) {
            mLog.debug("mTransData.getLatitude() {}",mTransData.getLatitude());
            if(mTransData.getLatitude() == null||mTransData.getLongitude() == null){
                mView.showCheckGPSFail();
                return null;
            }
        }*/
        return joinPoint.proceed();
    }

    @Override
    public void onLocation(AMapLocation location) {
        if(location == null){
            mRepository.setParamValue(PreferencesConstants.LONGITUDE,"0.0");
            mRepository.setParamValue(PreferencesConstants.LATITUDE,"0.0");
            mLog.debug("获取定位失败");
        }else{
            mLog.debug("经    度    : {}",location.getLongitude());
            mLog.debug("纬    度    : {}",location.getLatitude());
            mLog.debug("经    度   str : {}",String.valueOf(location.getLongitude()));
//            mTransData.setLongitude(String.valueOf(location.getLongitude()));
//            mTransData.setLatitude(String.valueOf(location.getLatitude()));
            mRepository.setParamValue(PreferencesConstants.LONGITUDE,String.valueOf(location.getLongitude()));
            mRepository.setParamValue(PreferencesConstants.LATITUDE,String.valueOf(location.getLatitude()));
            mRepository.syncParamValue();
        }
    }
}
